package com.wx.house.manager.api.permission.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import com.wx.house.manager.api.permission.service.SysMenusService;
import com.wx.house.manager.api.permission.text.MenusIDStateDto;
import com.wx.house.manager.api.permission.text.MenusPame;
import com.wx.house.manager.api.permission.text.MenusUpdate;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.wx.house.common.base.BaseController;
import com.wx.house.common.exception.BusinessException;
import com.wx.house.common.util.IDUtils;
import com.wx.house.common.util.JwtUtils;
import com.wx.house.common.util.StringUtil;
import com.wx.house.core.pojo.base.BasePage;
import com.wx.house.core.pojo.base.Result;
import com.wx.house.core.pojo.po.SysMenus;
import com.wx.house.core.pojo.vo.SysMenusVo;

import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

@RestController
@RequestMapping("SysMenus/")
@Api(value = "菜单模块", tags = "模块:菜单管理")
@Slf4j
public class SysMenusController extends BaseController{
	@Resource
	private SysMenusService sysMenusService;
	
	@ApiOperation(value = "新增菜单", notes = "新增菜单")
	@PostMapping("addMenus/")
	public Result addMenus(@RequestBody @Validated MenusPame menusPame) {
		try {
			SysMenus sysMenus=SysMenus.builder()
					.id(IDUtils.genItemId(4)+"")
					.pId(menusPame.getPId())
                    .menuName(menusPame.getMenuName())
                    .url(menusPame.getUrl())
                    .ico(menusPame.getIco())
                    .remark(menusPame.getRemark())
                    .menuType(menusPame.getMenuType())
                    .state(0)
                    .menuOrder(menusPame.getMenuOrder())
                    .build();
			sysMenusService.addMenu(sysMenus);
			return Result.success();
		} catch (Exception e) {
			throw new BusinessException("添加失败");
		}
	}
	
	@ApiOperation(value = "查询全部菜单", notes = "查询全部菜单")
	@GetMapping("SelectMenus/")
	public Result<List<SysMenus>> SelectMenus(String MenuName,BasePage page,HttpServletRequest request) {
		try {
			List<SysMenus> sysMenus=sysMenusService.selectMenus(MenuName);
			return Result.success(sysMenus);
		} catch (Exception e) {
			throw new BusinessException("查询失败");
		}
	}
	
	@ApiOperation(value = "查询菜单名是否存在", notes = "查询菜单名是否存在")
	@GetMapping("getMenusName/")
	public Result getMenusName(String MenuName) {
		try {
			SysMenus sysMenus=	sysMenusService.getMenusName(MenuName);
			if(StringUtil.isNotEmpty(sysMenus))
			{
				return Result.error(null);
			}
		} catch (Exception e) {
			throw new BusinessException("查询菜单名失败");
		}
		return Result.success(null);
	}
	
	@ApiOperation(value = "更新菜单", notes = "更新菜单")
	@PutMapping("update/")
	public Result updateAdmin(@RequestBody @Validated MenusUpdate menusUpdate, HttpServletRequest request) {
		try {
			String token = request.getHeader("authorization");
			//step1. 解析token
			Claims claims = JwtUtils.builder().token(token).build().claims();
			//step2. 从token获取参数,管理员姓名
			String realName = claims.get("realName").toString();
			//存入sysRole，判断是否有值
			SysMenus sysMenus=new SysMenus();
			sysMenus.setId(menusUpdate.getId());
			//父id
			if (!StringUtils.isEmpty(menusUpdate.getPId()))
			{
				sysMenus.setPId(menusUpdate.getPId());
			}
			//菜单名字
			if (!StringUtils.isEmpty(menusUpdate.getMenuName()))
			{
				sysMenus.setMenuName(menusUpdate.getMenuName());
			}
			//url
			if (!StringUtils.isEmpty(menusUpdate.getUrl()))
			{
				sysMenus.setUrl(menusUpdate.getUrl());
			}
			//图标
			if (!StringUtils.isEmpty(menusUpdate.getIco()))
			{
				sysMenus.setIco(menusUpdate.getIco());
			}
			//备注
			if (!StringUtils.isEmpty(menusUpdate.getRemark()))
			{
				sysMenus.setRemark(menusUpdate.getRemark());
			}
			//类型
			if (menusUpdate.getMenuType() != null)
			{
				sysMenus.setMenuType(menusUpdate.getMenuType());
			}
			//序号
			if (menusUpdate.getMenuOrder() != null)
			{
				sysMenus.setMenuOrder(menusUpdate.getMenuOrder());
			}	
			sysMenus.setOperation(realName);
			sysMenus.setOperationTime(new Date());
			sysMenusService.updateMenu(sysMenus);
			return Result.success();
		} catch (Exception e) {
			e.printStackTrace();
			throw new BusinessException("更新失败");
		}
	}
	@ApiOperation(value = "禁用菜单(禁用1/启用0)", notes = "禁用菜单（传入的sysMenusId）")
	@PutMapping("delete/")
	public Result deleteMenus(@RequestBody @Validated MenusIDStateDto menusIDStateDto) {
		try {
			if("0".equals(menusIDStateDto.getState()))
			{
				sysMenusService.DeleteMenus(menusIDStateDto.getSysMenusId(), 0 );
			}
			else if ("1".equals(menusIDStateDto.getState())) {
				sysMenusService.DeleteMenus(menusIDStateDto.getSysMenusId(), 1 );
			}
			else {
				throw new BusinessException("参数错误");
			}
			return Result.success();
		} catch (Exception e) {
			throw new BusinessException("失败");
		}
	}
	@ApiOperation(value = "删除菜单", notes = "删除菜单（传入的sysMenusId）")
	@DeleteMapping("deleteMenus/{sysMenusId}")
	public Result deleteMenuseId(@PathVariable String sysMenusId) {
		try {
			sysMenusService.DeleteMenuseId(sysMenusId);
			return Result.success();
		} catch (Exception e) {
			throw new BusinessException("失败");
		}
	}
	/***
	 * 查询菜单树
	 */
	@ApiOperation(value = "查询全部菜单树", notes = "查询全部菜单树")
	@GetMapping("SeleMenusTree/")
    public Result<List<SysMenusVo>> getTree() {
    	List<SysMenusVo> Menus=sysMenusService.sysMenuslist();
        List<SysMenusVo> baseLists = new ArrayList<>();
        // 总菜单，出一级菜单，一级菜单没有父id
        for (SysMenusVo e: Menus) {
            if( "0".equals(e.getPId())){
                baseLists.add( e );
            }
        }
        // 遍历一级菜单
        for (SysMenusVo e: baseLists) {
            // 将子元素 set进一级菜单里面
            e.setChild( getChild(e.getId(),Menus) );
        }
        return Result.success(baseLists);
    }
    public List<SysMenusVo> getTree1(String menuId) {
    	List<SysMenusVo> Menus=sysMenusService.sysMenuslist();
        List<SysMenusVo> baseLists = new ArrayList<>();
        // 总菜单，出一级菜单，一级菜单没有父id
        for (SysMenusVo e: Menus) {
            if( menuId.equals(e.getId())){
                baseLists.add( e );
            }
        }
        // 遍历一级菜单
        for (SysMenusVo e: baseLists) {
            // 将子元素 set进一级菜单里面
            e.setChild( getChild(e.getId(),Menus) );
        }
        return  baseLists;
    }
    /**
     * 获取子节点
     * @param pid
     * @param elements
     * @return
     */
    private List<SysMenusVo> getChild(String pid , List<SysMenusVo> elements){
        List<SysMenusVo> childs = new ArrayList<>();
        for (SysMenusVo e: elements) {
            if(!"0".equals(e.getPId())){
                if(e.getPId().equals( pid )){
                    // 子菜单的下级菜单
                    childs.add( e );
                }
            }
        }
        // 把子菜单的子菜单再循环一遍
        for (SysMenusVo e: childs) {
            // 继续添加子元素
            e.setChild( getChild( e.getId() , elements ) );
        }
        //停下来的条件，如果 没有子元素了，则停下来
        if( childs.size()==0 ){
            return null;
        }
        return childs;
    }
}